package com.boarsoft.boar.sequence.snowflake;

import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import com.boarsoft.boar.sequence.service.SnowflakeService;
import com.boarsoft.common.util.InetUtil;

public class WorkerIdKeeper implements Runnable {

	protected SnowflakeService snowflakeService;

	private String appName;

	private Map<String, SnowflakeIdWorker> workerMap = new ConcurrentHashMap<>();

	protected ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

	public WorkerIdKeeper(SnowflakeService snowflakeService, ScheduledExecutorService scheduler, String appName,
			Map<String, SnowflakeIdWorker> workerMap) {
		this.snowflakeService = snowflakeService;
		this.scheduler = scheduler;
		this.appName = appName;
		this.workerMap = workerMap;
		scheduler.execute(this);
	}

	public void run() {
		if (snowflakeService == null) {
			return;
		}
		if (workerMap == null || workerMap.isEmpty()) {
			return;
		}
		Set<String> tags = new HashSet<>();
		for (Entry<String, SnowflakeIdWorker> en : workerMap.entrySet()) {
			SnowflakeIdWorker w = en.getValue();
			tags.add(w.getId());
		}
		snowflakeService.refresh("-1", InetUtil.getAddr(), appName, workerMap.keySet(), tags);
	}

	public SnowflakeService getSnowflakeService() {
		return snowflakeService;
	}

	public void setSnowflakeService(SnowflakeService snowflakeService) {
		this.snowflakeService = snowflakeService;
	}

	public String getAppName() {
		return appName;
	}

	public void setAppName(String appName) {
		this.appName = appName;
	}

	public Map<String, SnowflakeIdWorker> getWorkerMap() {
		return workerMap;
	}

	public void setWorkerMap(Map<String, SnowflakeIdWorker> workerMap) {
		this.workerMap = workerMap;
	}

	public ScheduledExecutorService getScheduler() {
		return scheduler;
	}

	public void setScheduler(ScheduledExecutorService scheduler) {
		this.scheduler = scheduler;
	}
}
